package com.supor.aiot.mine.ui.ips;

import android.annotation.SuppressLint;
import android.app.Application;
import android.text.TextUtils;

import com.android.baseconfig.common.utils.GsonUtil;
import com.android.baseconfig.common.utils.Logc;
import com.google.gson.reflect.TypeToken;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.api.FileUploadImpl;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.entity.ProductCategory;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.common.entity.UploadResultBean;
import com.supor.aiot.mine.R;
import com.supor.aiot.mine.api.IpsImpl;
import com.supor.aiot.mine.bean.ImageItem;
import com.supor.aiot.mine.bean.IpsBean;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

public class AddIpsViewModel extends BaseViewModel {

    private MutableLiveData<Result> addResult = new MutableLiveData<>();
    private MutableLiveData<Result> uploadResult = new MutableLiveData<>();
    private MutableLiveData<List<String>> urlArray = new MutableLiveData<>();
    private List<String> photoPaths;
    private List<String> videoPaths;
    private List<String> urlList;


    public AddIpsViewModel(@NonNull Application application) {
        super(application);
    }

    public MutableLiveData<Result> getAddResult() {
        return addResult;
    }

    public MutableLiveData<Result> getUploadResult() {
        return uploadResult;
    }

    public MutableLiveData<List<String>> getUrlArray() {
        return urlArray;
    }

    @SuppressLint("CheckResult")
    public void addIps(IpsBean ipsBean) {
        IpsImpl.getInstance().addIps(ipsBean).subscribe(result -> {
            if (result.isSuccess()) {
                addResult.setValue(new Result.Success(null));
            } else {
                addResult.setValue(new Result.Error("添加创意失败"));
            }
        }, throwable -> {
            Logc.e("添加创意失败: " + throwable.getMessage());
            addResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    public void uploadFile(String localPhotoUrl, String localVideoUrl) {
        urlList = new ArrayList<>();
        photoPaths = new ArrayList<>();
        videoPaths = new ArrayList<>();
        if (!TextUtils.isEmpty(localPhotoUrl)) {
            photoPaths.add(localPhotoUrl);
        }
        if (!TextUtils.isEmpty(localVideoUrl)) {
            videoPaths.add(localVideoUrl);
        }

        if (photoPaths.size() != 0) {
            uploadPhoto(photoPaths);
        } else if (videoPaths.size() != 0) {
            uploadVideo(videoPaths);
        } else {
            urlArray.setValue(urlList);
        }
    }

    public void uploadFile(List<ImageItem> itemList) {
        urlList = new ArrayList<>();
        photoPaths = new ArrayList<>();
        videoPaths = new ArrayList<>();
        for (int i = 0; i < itemList.size() - 2; i++) {
            photoPaths.add(itemList.get(i).imagePath);
        }
        if (!Constants.ADD_VIDEO.equalsIgnoreCase(itemList.get(itemList.size() - 1).imagePath)) {
            videoPaths.add(itemList.get(itemList.size() - 1).imagePath);
        }
        if (!Constants.ADD_PHOTO.equalsIgnoreCase(itemList.get(itemList.size() - 2).imagePath)) {
            photoPaths.add(itemList.get(itemList.size() - 2).imagePath);
        }

        if (photoPaths.size() != 0) {
            uploadPhoto(photoPaths);
        } else if (videoPaths.size() != 0) {
            uploadVideo(videoPaths);
        } else {
            urlArray.setValue(urlList);
        }
    }

    /**
     * 上传图片
     *
     * @param pathList 图片路径列表
     */
    @SuppressLint("CheckResult")
    public void uploadPhoto(final List<String> pathList) {
        List<File> files = new ArrayList<>();
        for (String s : pathList) {
            File file = new File(s);
            files.add(file);
        }
        FileUploadImpl.getInstance().uploadFiles("photo", files).subscribe(result -> {
            Logc.i("uploadFiles: " + result);
            JSONObject jsonObject = new JSONObject(result);
            if ("success".equalsIgnoreCase(jsonObject.getString("result"))) {
                List<UploadResultBean> uploadResultBeans =
                        GsonUtil.getInstance().toObject(jsonObject.getString("fileUrls"),
                                new TypeToken<List<UploadResultBean>>() {
                                }.getType());
                if (uploadResultBeans.size() > 0) {
                    for (UploadResultBean uploadResultBean : uploadResultBeans) {
                        urlList.add(uploadResultBean.getFileUrl());
                    }
                }
                if (videoPaths != null && videoPaths.size() != 0) {
                    uploadVideo(videoPaths);
                } else {
                    urlArray.setValue(urlList);
                }
            } else {
                uploadResult.setValue(new Result.Error("upload photo failed"));
            }
        }, throwable -> {
            Logc.e("uploadFiles: " + throwable);
            uploadResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    /**
     * 上传图片
     *
     * @param pathList 图片路径列表
     */
    @SuppressLint("CheckResult")
    public void uploadVideo(final List<String> pathList) {
        List<File> files = new ArrayList<>();
        for (String s : pathList) {
            File file = new File(s);
            files.add(file);
        }
        FileUploadImpl.getInstance().uploadFiles("video", files).subscribe(result -> {
            Logc.i("uploadFiles: " + result);
            JSONObject jsonObject = new JSONObject(result);
            if ("success".equalsIgnoreCase(jsonObject.getString("result"))) {
                List<UploadResultBean> uploadResultBeans =
                        GsonUtil.getInstance().toObject(jsonObject.getString("fileUrls"),
                                new TypeToken<List<UploadResultBean>>() {
                                }.getType());
                if (uploadResultBeans.size() > 0) {
                    for (UploadResultBean uploadResultBean : uploadResultBeans) {
                        urlList.add(uploadResultBean.getFileUrl());
                    }
                }
                urlArray.setValue(urlList);
            } else {
                uploadResult.setValue(new Result.Error("upload video failed"));
            }
        }, throwable -> {
            Logc.e("uploadFiles: " + throwable);
            uploadResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }

    public List<ProductCategory> getCategory() {
        List<ProductCategory> categoryList = new ArrayList<>();
        ProductCategory category = new ProductCategory();
        category.categoryName = "电炊品类";
        List<ProductType> productTypeList = new ArrayList<>();
        productTypeList.add(new ProductType("电饭煲", "RC", "E0", R.mipmap.device_rice_cooker));
        productTypeList.add(new ProductType("电炖锅", "ES", "F0", R.mipmap.device_stewpot));
        productTypeList.add(new ProductType("主厨机(旗舰版)", "EPC", "SY-50MT01", R.mipmap.device_chef_machine01));
        productTypeList.add(new ProductType("主厨机(标准版)", "EPC", "SY-50MT10", R.mipmap.device_chef_machine10));
        productTypeList.add(new ProductType("电压力锅", "EPC", "A1", R.mipmap.device_pressure_cooker));
        productTypeList.add(new ProductType("电炸锅", "Deep Fryer", "A2", R.mipmap.device_fryer));
        productTypeList.add(new ProductType("空气炸锅", "AF", "A3", R.mipmap.device_air_fryer));
        productTypeList.add(new ProductType("空气烤箱", "", "A4", R.mipmap.device_air_oven));
        productTypeList.add(new ProductType("小煮锅系列", "", "A5", R.mipmap.device_small_cooking_pot));
        // productTypeList.add(new ProductType("炖锅", "", "A6", R.mipmap.device_chef_machine));
        category.productTypes = productTypeList;
        categoryList.add(category);

        category = new ProductCategory();
        category.categoryName = "厨房大家电";
        productTypeList = new ArrayList<>();
        productTypeList.add(new ProductType("蒸烤一体机(MY85)", "ZKQD", "MY85", R.mipmap.device_oven85));
        productTypeList.add(new ProductType("蒸烤一体机(MY88)", "ZKQD", "MY88", R.mipmap.device_oven88));
        category.productTypes = productTypeList;
        categoryList.add(category);

        category = new ProductCategory();
        category.categoryName = "电磁电动品类";
        productTypeList = new ArrayList<>();
        productTypeList.add(new ProductType("破壁机", "PF", "C0", R.mipmap.device_broken_food_processor));
        productTypeList.add(new ProductType("电陶炉", "", "C1", R.mipmap.device_radiant_cooker));
        productTypeList.add(new ProductType("料理机", "", "C2", R.mipmap.device_food_processor));
        productTypeList.add(new ProductType("电磁炉", "IH", "C3", R.mipmap.device_induction_cooker));
        productTypeList.add(new ProductType("豆浆机", "", "C4", R.mipmap.device_soymilk_machine));
        productTypeList.add(new ProductType("原汁机", "", "C5", R.mipmap.device_juice_machine));
        // productTypeList.add(new ProductType("搅拌机", "BL", "C6", R.mipmap.device_mixer));
        productTypeList.add(new ProductType("手持搅拌机", "HBL", "C7", R.mipmap.device_mixer));
        productTypeList.add(new ProductType("打蛋机", "HM", "C8", R.mipmap.device_egg_breaking));
        productTypeList.add(new ProductType("绞肉机", "JR", "C9", R.mipmap.device_meat_grinder));
        productTypeList.add(new ProductType("辅食机", "", "CA", R.mipmap.device_baby_cook));
        productTypeList.add(new ProductType("随行杯", "", "CB", R.mipmap.device_tumbler));
        category.productTypes = productTypeList;
        categoryList.add(category);

        category = new ProductCategory();
        category.categoryName = "饮品类";
        productTypeList = new ArrayList<>();
        productTypeList.add(new ProductType("电水壶", "Kettle", "D0", R.mipmap.device_kettle));
        productTypeList.add(new ProductType("养生壶", "", "D1", R.mipmap.device_health_pot));
        productTypeList.add(new ProductType("养生杯", "", "D2", R.mipmap.device_health_cup));
        productTypeList.add(new ProductType("咖啡机", "FCM", "D3", R.mipmap.device_coffee_machine));
        productTypeList.add(new ProductType("多士炉", "Toaster", "D4", R.mipmap.device_toaster));
        category.productTypes = productTypeList;
        categoryList.add(category);

        category = new ProductCategory();
        category.categoryName = "其他";
        productTypeList = new ArrayList<>();
        productTypeList.add(new ProductType("新品类", "Z", "Z", R.mipmap.ic_other_product_unselect));
        category.productTypes = productTypeList;
        categoryList.add(category);

        return categoryList;
    }
}
